package br.com.gsc.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import br.com.gsc.model.tableMapping.Person;
import br.com.gsc.model.tableMapping.Post;
import br.com.gsc.model.tableMapping.Topic;
import br.com.gsc.repository.objRepos.PersonRepository;
import br.com.gsc.repository.objRepos.PostRepository;
import br.com.gsc.repository.objRepos.TopicRepository;

@Controller
@RequestMapping("/{companyId}/produto/{productId}/topico/{topicId}/post/**")
public class PostController {
	
	@Autowired
	PostRepository postRepo;
	@Autowired
	PersonRepository personRepo;
	@Autowired
	TopicRepository topicRepo;
	@Autowired
	@Qualifier("authentication")
	private Authentication auth;
	
//	@RequestMapping(value = "/{companyId}/produto/{productId}/topico/{topicId}/post/{postId}", method=RequestMethod.GET)
//	public ModelAndView showPosts(@PathVariable("postId") long id){
//		ModelAndView model = new ModelAndView("/user/post");
//		return null;
//	}
	
	@RequestMapping(value = "/{companyId}/produto/{productId}/topico/{topicId}/post/addpost", method=RequestMethod.POST)
	public ModelAndView addPost(@PathVariable(value="topicId") long topicId, @ModelAttribute("post") Post post,
						  @PathVariable("companyId") long compId,
						  @PathVariable("productId") long prodId
	){
		ModelAndView model = null;
		if(auth.isAuthenticated() && !auth.getName().equals("anonymousUser")){			
			model = new ModelAndView();
			Person person = personRepo.findPersonByID(auth.getName());
			post.setPerson(person);
			Topic topic = topicRepo.findTopicByID(topicId);
			post.setTopic(topic);
			post.setCreatedIn(new Date());
			postRepo.addPost(post);
			model.setViewName("redirect:/"+compId+"/produto/"+prodId+"/topico/"+topicId+".html");
			return model;
		}else{
			return new ModelAndView("forward:/loginform.html");
		}
			
	}
	
	@RequestMapping(value = "/{companyId}/produto/{productId}/topico/{topicId}/post/{postId}", method=RequestMethod.DELETE)
	public String deletePost(@PathVariable(value="topicId") long topicId, @PathVariable(value="postId") long postId,
			  				 @PathVariable("companyId") long compId,
			  				 @PathVariable("productId") long prodId		
	){
		postRepo.removePost(postRepo.findTPostByID(postId));
		return "redirect:/"+compId+"/produto/"+prodId+"/topico/"+topicId+".html";
	}

}
